#!/usr/bin/env python
from calibre.web.feeds.news import BasicNewsRecipe, classes


class MoneyControlRecipe(BasicNewsRecipe):
    title = u'Money Control'
    __author__ = 'unkn0wn'
    description = 'Read the latest business news on the Indian economy, global market, upcoming IPOs and more.'
    language = 'en_IN'
    masthead_url = 'https://images.moneycontrol.com/images/ftpopup/moneyloginlogo.png'
    encoding = 'utf-8'
    no_stylesheets = True
    remove_javascript = True
    remove_attributes = ['width', 'height', 'float', 'style']

    ignore_duplicate_articles = {'title', 'url'}
    remove_empty_feeds = True
    resolve_internal_links = True
    oldest_article = 1  # days

    extra_css = '''
        img {display:block; margin:0 auto;}
        .article_image_wrapper { font-size:small; text-align:center; }
        .articlename_join_follow, .author_wrapper, .FT_block_article { font-size:small; color:#404040; }
        .article_desc { font-style:italic; color:#202020; }
    '''

    keep_only_tags = [
        dict(name='div', attrs={'id':lambda x: x and x.startswith('article-')})
    ]

    remove_tags = [
        dict(name=['svg', 'style', 'button', 'script']),
        dict(attrs={'id':['social_icon_impression', 'taboola-mid-article-thumbnails']}),
        classes(
            'social_icons_wrapper mid-arti-ad lastPara related_stories_left_block social_icons_mobile_wrapper '
            'advSlotsWithoutGrayBox tags_wrapper maintextdiv page_right_wrapper stockwidget tech_newsletter'
        )
    ]

    def preprocess_html(self, soup):
        desc = soup.find(**classes('article_desc'))
        if desc:
            desc.name = 'p'
        for wrap in soup.findAll(**classes('article_image_wrapper')):
            for h2 in wrap.findAll('h2'):
                h2.name = 'span'
        for img in soup.findAll('img', attrs={'data-src':True}):
            img['src'] = img['data-src']
        return soup

    def parse_index(self):
        index = 'https://www.moneycontrol.com/'

        business_sections = [
            'markets', 'stocks', 'ipo', 'budget', 'banks', 'moneycontrol-research', 'economy', 'earnings', 'real-estate',
            'personal-finance', 'commodities', 'trade', 'companies'
        ]

        news_sections = [
            'india', 'world', 'opinion', 'politics', 'technology', 'trends', 'lifestyle'
        ]

        feeds = []
        soup = self.index_to_soup(index)
        for b_sec in business_sections:
            burl = index + 'news/business/'
            section = b_sec.capitalize()
            self.log(section)
            articles = []
            for a in soup.findAll('a', attrs={'href':lambda x: x and x.startswith(burl + b_sec + '/')}):
                url = a['href']
                if url in {burl + b_sec + '/', burl + b_sec}:
                    continue
                title = self.tag_to_string(a)
                self.log('\t', title, '\n\t\t', url)
                articles.append({'title': title, 'url': url})
            if articles:
                feeds.append((section, articles))
        for n_sec in news_sections:
            nurl = index + 'news/'
            nsection = n_sec.capitalize()
            self.log(nsection)
            articles = []
            for a in soup.findAll('a', attrs={'href':lambda x: x and x.startswith(nurl + n_sec + '/')}):
                url = a['href']
                if url in {nurl + n_sec + '/', nurl + n_sec}:
                    continue
                title = self.tag_to_string(a)
                self.log('\t', title, '\n\t\t', url)
                articles.append({'title': title, 'url': url})
            if articles:
                feeds.append((nsection, articles))
        return feeds

    def populate_article_metadata(self, article, soup, first):
        desc = soup.find(**classes('article_desc'))
        if desc:
            article.summary = self.tag_to_string(desc)
            article.text_summary = article.summary
